package me.leiusual.sharing.ui.product.dialog

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.dialog_product_optional.*
import kotlinx.android.synthetic.main.layout_amount.view.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.ProductDetail
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.base.AbstractBottomSheetDialog
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.product.ProductDetailFragmentDirections
import me.leiusual.sharing.ui.product.adapter.ProductOptionalAdapter
import me.leiusual.sharing.ui.product.adapter.ProductOptionalViewHolder
import me.leiusual.sharing.util.extension.*
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
class ProductOptionalDialog : AbstractBottomSheetDialog(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: ProductOptionalViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.dialog_product_optional, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    // 可选属性
    recycler_view.adapter = ProductOptionalAdapter(object : ProductOptionalViewHolder.Listener {

      override fun onTagClicked() {

        // 更新列表
        recycler_view.adapter?.notifyDataSetChanged()

        // 当前选中
        val currentSku = mutableMapOf<Long, Long>().apply {
          mainViewModel.productDetail.requireValue.optionList.forEach { option ->
            option.productOptionValues.forEach { optionValue ->
              if (optionValue.checked) {
                put(option.id, optionValue.id)
              }
            }
          }
        }

        // 查询当前对应的Sku，临存
        val productSku = mainViewModel.productDetail.requireValue.skus.find { sku ->
          sku.sku == currentSku
        }
        if (productSku != null) {
          viewModel.productSku(productSku)
        }
      }
    })

    // 确认
    button_confirm.setOnClickListener(this)

    observeData()
  }

  private fun observeData() {
    mainViewModel.productDetail.observe(viewLifecycleOwner, Observer {
      Timber.v("productDetail = %s", it)

      // 更新产品基本信息
      doUpdateProductDetail(it)

      // 查询当前对应的Sku，临存
      val productSku = it.skus.find { sku ->
        sku.sku == it.currentSku
      }
      if (productSku != null) {
        viewModel.productSku(productSku)
      }
    })

    viewModel.productSku.observe(viewLifecycleOwner, Observer {
      Timber.v("productSku = %s", it)

      // 查找当前对应的Mia，临存
      val productMia = mainViewModel.productDetail.requireValue.allMia.find { mia ->
        mia.id == it.miaId
      }
      if (productMia != null) {
        viewModel.productMia(productMia)
      }
    })

    viewModel.productMia.observe(viewLifecycleOwner, Observer {
      Timber.v("productMia = %s", it)

      // 更新价格库存
      doUpdatePriceStorage(it)
    })

    viewModel.cartAdd.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("cartAdd = %s", it)
      when (it) {
        is Data.Loading -> {
          button_confirm.isEnabled = false
        }
        is Data.Error -> {
          button_confirm.isEnabled = true
          toast(it.error.message)
        }
        is Data.Success -> {
          button_confirm.isEnabled = true
          toast("加入成功")

          // 退出
          dismiss()
        }
      }
    })
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_confirm -> {

        // 检查登录
        if (!viewModel.token.isLogin) {
          val navDirections = ProductDetailFragmentDirections.actionGlobalAccountLoginFragment()
          requireParentFragment().findNavController().navigate(navDirections)
          return
        }

        // 加入购物车
        val mia = viewModel.productMia.value
        if (mia == null) {
          toast("无效商品")
          return
        }
        val quantity = amount_view.etAmount.text.toString().toIntOrNull() ?: 1
        val r = mainViewModel.productDetail.requireValue.referStoreId
        viewModel.cartAdd(mia.id, quantity, r)
      }
    }
  }

  /**
   * 更新商品基本信息
   */
  private fun doUpdateProductDetail(it: ProductDetail) {

    // 图片
    image_view.setImageUrl(it.product.picture)

    // 名称
    text_view_product_name.text = it.product.name

    // 可选列表
    it.optionList.forEach { option ->
      option.productOptionValues.forEach { optionValue ->
        if (it.currentSku[option.id] == optionValue.id) {
          optionValue.checked = true
        }
      }
    }
    val adapter = recycler_view.adapter as ProductOptionalAdapter
    adapter.submitList(it.optionList, it.skus)
  }

  /**
   * 更新商品库存
   */
  private fun doUpdatePriceStorage(mia: ProductDetail.Mia) {

    // 价格
    val size = 10f.spToPx(requireContext())
    val builder = StringBuilder()
    builder.append("""<font color="red">""")
    builder.append("""<size_$size>￥</size_$size>""")
    builder.append(mia.coinAmount)
    if (mia.pointCoins > 0) {
      builder.append("""<size_$size> + 分</size_$size>""")
      builder.append(mia.pointCoins)
    }
    builder.append("""</font>""")
    text_view_price.text = builder.toString().toSpanned()

    // 库存
    text_view_inventory.text = "库存${mia.sellingCount}件"

    // 购买数量库存限制
    amount_view.minAmount = mia.minPurchaseAmount
    amount_view.etAmount.setText(mia.minPurchaseAmount.toString())
    amount_view.maxAmount = mia.sellingCount
  }
}